package com.bdqn.qnnews.article.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bdqn.qnnews.article.entity.ApArticle;
import com.bdqn.qnnews.article.mapper.ApArticleMapper;
import com.bdqn.qnnews.article.service.ArticleFreemarkerService;
import com.bdqn.qnnews.minio.utils.MinioUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    //在测试环境注入时会有红色下划线，不影响功能
    private final Configuration configuration;
    private final MinioUtil minioUtil;
    private final ApArticleMapper apArticleMapper;
    
    @Override
    public void buildArticleToMinIo(ApArticle apArticle, String content) {
        if(StringUtils.isNotEmpty(content)){
            try {
                //加载文章详情页模板，默认从类路径下加载
                //模板制作过程：  前端设计静态页面 -> 后端开发拿到静态页面在合适的位置加上Freemarker的标签 -> 得到模板
                Template template = configuration.getTemplate("articleContent.ftl");

                //创建Map集合存储模板需要的数据
                Map<String,Object> data = new HashMap<>();
                List<Map> articleContent = JSONUtil.toList(content,Map.class);
                data.put("content",articleContent);

                //生成静态页数据
                //临时字符串缓存流
                StringWriter writer = new StringWriter();
                template.process(data,writer);

                //把静态页数据存储到MinIO，获取到页面的url地址
                String fileName = apArticle.getId()+".html";
                InputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
                String url = minioUtil.uploadHtmlFile("",fileName,inputStream);

                //把url地址更新到文章表的static_url字段上
                apArticle.setStaticUrl(url);
                apArticleMapper.updateById(apArticle);
                
            } catch (Exception e) {
                e.printStackTrace();
                log.error("生成静态页失败，{}",e.getMessage());
            } 
        }
    }
}